package boardgamer.common.client;

import android.graphics.Canvas;
import android.graphics.RectF;
import android.view.MotionEvent;
import boardgamer.common.client.layout.LayoutGroup;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 * @author garysoed
 */
public class ToggleButton implements Button {

  private final Button buttonOn;
  private final Button buttonOff;
  private final LayoutGroup displayGroup;
  private boolean isActive;

  public ToggleButton(Button buttonOn, Button buttonOff, boolean isActive) {
    this.buttonOn = checkNotNull(buttonOn, "buttonOn");
    this.buttonOff = checkNotNull(buttonOff, "buttonOff");
    this.isActive = isActive;

    this.displayGroup = new LayoutGroup()
        .add(buttonOn).atCurrentRect()
        .add(buttonOff).atCurrentRect()
        .horizontalAlign(LayoutGroup.HorizontalAlign.CENTER)
        .verticalAlign(LayoutGroup.VerticalAlign.CENTER);
  }

  public ToggleButton(Button displayOn, Button displayOff) {
    this(displayOn, displayOff, true /* isActive */);
  }

  @Override
  public void draw(Canvas canvas) {
    if (isActive) {
      buttonOn.draw(canvas);
    } else {
      buttonOff.draw(canvas);
    }
  }

  public boolean isActive() {
    return isActive;
  }

  public void toggleDisplay() {
    isActive = !isActive;
  }

  @Override
  public void handleEvent(float eventX, float eventY, int eventAction) {
    HasEventHandler activeButton = isActive ? buttonOn : buttonOff;
    activeButton.handleEvent(eventX, eventY, eventAction);

    if (activeButton.getCollisionBox().contains(eventX, eventY)
        && eventAction == MotionEvent.ACTION_UP) {
      toggleDisplay();
    }
  }

  @Override
  public RectF getCollisionBox() {
    return isActive
        ? buttonOn.getCollisionBox()
        : buttonOff.getCollisionBox();
  }

  @Override
  public void setBoundingRect(RectF boundingRect) {
    displayGroup.setBoundingRect(boundingRect);
  }

  @Override
  public RectF getBoundingRect() {
    return new RectF(displayGroup.getBoundingRect());
  }
}
